# views.py
from django.http import JsonResponse
from tools.models.models import Product, Product2
from django.shortcuts import render


def product_search(request):
    # 获取查询参数
    category = request.GET.get('category')

    # 查询数据库
    products = Product.objects.filter(category=category) if category else Product.objects.all()

    # 序列化数据
    results = [{"id": p.id, "name": p.name, "price": str(p.price)} for p in products]

    return JsonResponse(results, safe=False)






# def product_list(request):
#     """显示产品列表页面"""
#     return render(request, '../templates/testing/product_list.html')
#
#
# def search_products(request):
#     """处理Ajax查询请求"""
#     query = request.GET.get('query', '')
#     category = request.GET.get('category', '')
#
#     # 基础查询集
#     products = Product2.objects.all()
#
#     # 应用搜索过滤
#     if query:
#         products = products.filter(name__icontains=query)
#
#     # 应用分类过滤
#     if category:
#         products = products.filter(category=category)
#
#     # 构建返回数据
#     product_list = []
#     for product in products:
#         product_list.append({
#             'id': product.id,
#             'name': product.name,
#             'category': product.category,
#             'price': str(product.price),
#             'description': product.description
#         })
#
#     return JsonResponse({'products': product_list})







# from django.shortcuts import render
# from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# from django.core.exceptions import ValidationError
# from .models import Product
import json


def product_list(request):
    """显示产品列表页面"""
    # 获取所有分类用于前端下拉框
    categories = Product2.objects.values_list('category', flat=True).distinct()
    return render(request, '../templates/testing/product_list.html', {'categories': categories})


def search_products(request):
    """处理Ajax查询请求"""
    query = request.GET.get('query', '')
    category = request.GET.get('category', '')

    # 基础查询集
    products = Product2.objects.all()

    # 应用搜索过滤
    if query:
        products = products.filter(name__icontains=query)

    # 应用分类过滤
    if category:
        products = products.filter(category=category)

    # 构建返回数据
    product_list = []
    for product in products:
        product_list.append({
            'id': product.id,
            'name': product.name,
            'category': product.category,
            'price': str(product.price),
            'description': product.description
        })

    return JsonResponse({'products': product_list})


@csrf_exempt
def add_product(request):
    """处理Ajax新增产品请求"""
    if request.method == 'POST':
        try:
            # 解析请求数据
            data = json.loads(request.body)

            # 验证必要字段
            required_fields = ['name', 'category', 'price', 'description']
            for field in required_fields:
                if field not in data or not data[field]:
                    return JsonResponse(
                        {'success': False, 'message': f'请填写{field}字段'},
                        status=400
                    )

            # 创建新产品
            product = Product2(
                name=data['name'],
                category=data['category'],
                price=data['price'],
                description=data['description']
            )

            # 保存到数据库
            product.save()

            # 返回成功响应
            return JsonResponse({
                'success': True,
                'message': '产品添加成功',
                'product': {
                    'id': product.id,
                    'name': product.name,
                    'category': product.category,
                    'price': str(product.price),
                    'description': product.description
                }
            })

        except json.JSONDecodeError:
            return JsonResponse(
                {'success': False, 'message': '无效的请求数据'},
                status=400
            )
        except ValidationError as e:
            return JsonResponse(
                {'success': False, 'message': str(e)},
                status=400
            )
        except Exception as e:
            return JsonResponse(
                {'success': False, 'message': f'添加失败: {str(e)}'},
                status=500
            )

    return JsonResponse(
        {'success': False, 'message': '不支持的请求方法'},
        status=405
    )


@csrf_exempt
def edit_product(request, id):
    if request.method == 'GET':
        try:
            product = Product2.objects.get(id=id)
            return JsonResponse({
                'success': True,
                'product': {
                    'id': product.id,
                    'name': product.name,
                    'category': product.category,
                    'price': product.price,
                    'description': product.description
                }
            })
        except Product2.DoesNotExist:
            return JsonResponse({'success': False, 'message': '产品不存在'}, status=404)

    elif request.method == 'POST':
        try:
            data = json.loads(request.body)
            product = Product2.objects.get(id=id)

            # 验证数据
            if not data.get('name'):
                return JsonResponse({'success': False, 'message': '产品名称不能为空'}, status=400)

            if not data.get('category'):
                return JsonResponse({'success': False, 'message': '产品分类不能为空'}, status=400)

            try:
                price = float(data.get('price', 0))
                if price < 0:
                    raise ValueError
            except ValueError:
                return JsonResponse({'success': False, 'message': '请输入有效的价格'}, status=400)

            # 更新产品信息
            product.name = data.get('name')
            product.category = data.get('category')
            product.price = price
            product.description = data.get('description', '')
            product.save()

            return JsonResponse({'success': True, 'message': '产品更新成功'})

        except Product2.DoesNotExist:
            return JsonResponse({'success': False, 'message': '产品不存在'}, status=404)
        except Exception as e:
            return JsonResponse({'success': False, 'message': str(e)}, status=500)